<template>
    <div class="publishArticle">
      <a-form
        style="justify-content: end;margin-top:10px;"
        ref="formRef"
        layout="inline"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        >
            <a-form-item label="">
                <a-tooltip>
                  <template #title>
                    <span>巡检昨日文章推荐量为0</span>
                  </template>
                  <a-button  style="color: #4096ff" @click="onDayInspection" :loading="state.inspectionLoading">每日巡检<RedoOutlined /></a-button>
                </a-tooltip>
            </a-form-item>
            <a-form-item label="">
                <a-button  style="color: #4096ff" @click="onDataRefresh" :loading="state.refreshLoading">数据刷新<RedoOutlined /></a-button>
            </a-form-item>
            <a-form-item label="">
                <div style="margin-bottom: 16px;text-align: right;">
                <a-button type="primary" :disabled="!hasSelected" :loading="state.loading" @click="onPulish">
                    {{ title }}
                </a-button>
                </div>
            </a-form-item>
        </a-form>
    </div>
  </template>
  
<script setup lang="ts">
  import { userSiteArticleList, userSiteArticleDetails, articlePublish, userSiteArticleSetRelease, articleLists, articleWithdraw, articleRemove, user_editPrev } from '../api/article'
  import { Modal } from 'ant-design-vue';
  import { message } from 'ant-design-vue';
  import { createVNode } from 'vue';
  import { ref, reactive, computed, watch } from 'vue';
  import { RedoOutlined } from '@ant-design/icons-vue';
//   import { storage, sessionStorage } from '../utils/storage';
  import { GetuserInfo } from '../utils/ipcRequest';
  type Key = string | number;
  const formRef = ref()
  const labelCol = { span: 14 };
  const wrapperCol = { span: 10 };
  const title = ref('一键发布')
  const state = reactive<{
    selectedRowKeys: Key[];
    selectedRows: Key[];
    loading: boolean;
    refreshLoading: Boolean,
    inspectionLoading:boolean
  }>({
    selectedRowKeys: [], // Check here to configure the default column
    selectedRows: [],
    loading: false,
    refreshLoading: false,
    inspectionLoading: false
  });
  const selectData:any = ref([]) // 发布文章需要的参数数组
  const articleList:any = ref([]) // 获取选中文章数据
  const count: any = ref(0) // 计算选择个数
  const props:any = defineProps({
    selectedRows: {
      type: Array,
      required: true,
    },
    refreshLoading:{
      type: Boolean,
      required: true,
    },
    inspectionLoading:{
      type: Boolean,
      required: true,
    },
    isLoding:{
      type: Boolean,
      required: true,
    }
    // selectedRowKeys: {
    //   type: Array,
    //   required: true,
    // },
    // site_id: {
    //     type: Number,
    //     required: true,
    // }
  })
  const selectedRows = ref([])
  watch(() => props.selectedRows, (newValue,oldValue) => {
     console.log(newValue,oldValue, newValue.length)
     selectedRows.value = newValue
     if(selectedRows.value.length > 0) {
        articleList.value = []
        selectData.value = []
        count.value = 0
        onArticleList(0)
    }
  })
  watch(() => props.refreshLoading, (newValue) => {
     state.refreshLoading = newValue
  })
  watch(() => props.inspectionLoading, (newValue) => {
     state.inspectionLoading = newValue
  })
  watch(() => props.isLoding, (newValue) => {
    if(newValue) {
        title.value = '正在发布'
    } else {
        title.value = '一键发布'
    }
     state.loading = newValue
  })
  const emits = defineEmits(['refresh-data','stop-upload','clear-select-data','refresh-list','day-inspection-data'])
  const hasSelected = computed(() => props.selectedRows.length > 0 && props.selectedRows.length == selectData.value.length && !props.isLoding);
  // 获取文章列表
  const onArticleList = (idx) => {
    const executeNext = async (index) => {
        if(index >= selectedRows.value.length) {
            // 获取对象数组
            let resultData2 = articleList.value
            console.log('获取发布满足条件的：',resultData2)
            if(resultData2.length > 0) {
                for (let i in resultData2) {
                    // if(resultData2[i]['prev_status'] == 1) {
                    //     if(resultData2[i].cookie) {
                    //        onGetuserinfo('', '',resultData2[i].cookie,resultData2[i].site_id, i) // 从返回的header中解析出token
                    //     }
                    // } else {
                        
                    // }
                    selectData.value.push({
                        site_id: resultData2[i]['site_id'],
                        cookie: resultData2[i]['cookie'],
                        prev_status: resultData2[i]['prev_status'],
                        prev_time: resultData2[i]['prev_time'],
                        info: {},
                        articleId: resultData2[i]['article_id'],
                        fileLists: [],
                        modalOpen: false,
                        vertical_cover: resultData2[i]['vertical_cover'],
                        activity_list: resultData2[i]['activity_list'],
                        square_mission_List: resultData2[i]['square_mission_List']
                    })
                    const filePathJson = `images_${resultData2[i]['article_id']}.json`;
                    const result = await window.electron.ipcRenderer.invoke('json-directory', filePathJson);
                    console.log(result)
                    if (result.type == 2) {
                        let jsonData =  JSON.parse(result.urlArr)
                        console.log(jsonData)
                        if(jsonData.data.length == 0) {
                            window.electron.ipcRenderer.invoke('delete-file', filePathJson).then(res => {
                                console.log(res)
                                if(res.success) {
                                console.log('文件删除成功')
                                } else {
                                console.log('删除文件失败',res.message)
                                }
                            })
                            // message.warning('文件为空，请刷新重新上传');
                            resultData2[i]['isPublish'] = false
                            resultData2[i]['publishReason'] = '文件为空,请刷新'
                            resultData2[i]['errorColor3'] = 'error'
                            resultData2[i]['publishText'] = '发布失败'
                            state.loading = false;
                            title.value = '一键发布'
                            selectData.value = []
                            selectedRows.value = []
                            emits('clear-select-data');
                            emits('refresh-list');
                        } else {
                            selectData.value?.forEach((item: any, index:any) => {
                                if (resultData2[i]['article_id'] === item.articleId) {
                                    selectData.value[index]['fileLists'] = jsonData.data; // 替换为空的内容部分--给数组赋值
                                    selectData.value[index]['modalOpen'] = true
                                }
                            });
                            console.log('发布文章数组：', selectData.value)
                            onArticleDetails(resultData2[i]['article_id']) // 获取详情内容
                        }
                    }else if(result.type == 1) {
                        resultData2[i]['isPublish'] = false
                        resultData2[i]['publishReason'] = '未读取到文件'
                        resultData2[i]['errorColor3'] = 'error'
                        resultData2[i]['publishText'] = '发布失败'
                        state.loading = false;
                        title.value = '一键发布'
                        selectData.value = []
                        selectedRows.value = []
                        emits('clear-select-data');
                        emits('refresh-list');
                    } else {
                        console.log(`读取文件失败：${result.message}`);
                        resultData2[i]['isPublish'] = false
                        resultData2[i]['publishReason'] = `读取${filePathJson}文件失败`
                        resultData2[i]['errorColor3'] = 'error'
                        resultData2[i]['publishText'] = '发布失败'
                        state.loading = false;
                        title.value = '一键发布'
                        selectData.value = []
                        selectedRows.value = []
                        emits('clear-select-data');
                        emits('refresh-list');
                    }
                }
            } else {
                message.warning('没有文章可以发布');
                state.loading = false;
                title.value = '一键发布'
                selectData.value = []
                selectedRows.value = []
                emits('clear-select-data');
                emits('refresh-list');
            }
            return
        }
        const currentItem:any = selectedRows.value[index];
        userSiteArticleList({page: 1,limit: 15, siteId: currentItem.site_id}).then((response:any) => {
            const result = response.data.data
            processItems(result.data, index)
        }).catch(() => {
            setTimeout(() => {
               executeNext(index + 1)
            }, 2000)
        })
    }
    executeNext(idx)
  }
  // 默认获取是否有下载和上传
  const processItems = async (data:any, index:any) => {
    for (let i in data) {
        let path = `images_${data[i].article_id}`; // 从开始到点号位置截取字符串
        const result = await window.electron.ipcRenderer.invoke('list-directory', path); // 等待操作完成
        // console.log(result)
        // 处理结果或更新数组项
        if(Array.isArray(result.imageArr)) {
            if(result.imageArr.length != 0) {
                data[i]['isDownload'] = true
                data[i]['downloadReason'] = '已解压' // 将修改后的对象添加到新数组中
            } else {
                data[i]['isDownload'] = false
                data[i]['downloadReason'] = ''
            }
        } else {
            data[i]['isDownload'] = false
            data[i]['downloadReason'] = ''
        }

        // 获取图片文件
        let pathJson = `images_${data[i].article_id}.json`;
        const resFile = await window.electron.ipcRenderer.invoke('json-directory', pathJson); // 等待操作完成
        // console.log(resFile,'resFile')
        if(resFile.type == 2) {
            let jsonData = JSON.parse(resFile.urlArr)
            data[i]['isUpload'] = true
            data[i]['uploadReason'] = '已上传' // 将修改后的对象添加到新数组中
            data[i]['uploadText'] = '已上传'
            data[i]['imgNum'] = jsonData.data.length
        } else if(resFile.type == 1 && data[i]['is_release'] == 0 && data[i]['status'] == 50 && data[i]['img_status'] == 20 && data[i]['isDownload']) {
            data[i]['isUpload'] = false
            data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
            data[i]['uploadText'] = ''
        } else {
            data[i]['isUpload'] = false
            data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
            data[i]['uploadText'] = ''
        }
        data[i]['name'] = selectedRows.value[index]['name']
        data[i]['site_id'] = selectedRows.value[index]['site_id']
        data[i]['prev_status'] = selectedRows.value[index]['prev_status']
        data[i]['prev_time'] = selectedRows.value[index]['prev_time']
        data[i]['cookie'] = selectedRows.value[index]['port_config'] && selectedRows.value[index]['port_config']['cookie'] ? selectedRows.value[index]['port_config']['cookie'] : ''
        data[i]['activity_list'] = selectedRows.value[index]['activity_list']
        data[i]['square_mission_List'] = selectedRows.value[index]['square_mission_List']
    }
    let resultData:any = data.filter((item2:any) =>item2.is_release == 0 && item2.status == 50 && item2.img_status == 20 && item2.isDownload && item2.isUpload);
    if(resultData.length > 0){
        articleList.value.push(resultData[0])
    }
    onArticleList(index + 1)
    console.log('选择的数据：',articleList.value, resultData)
  };
  const onDayInspection = () => {
    emits('day-inspection-data');
  }

  // 数据刷新
  const onDataRefresh = () => {
    emits('refresh-data');
  }

  // 一键发布
  const onPulish = async () => {
    emits('stop-upload',{isUpload: true});
    state.loading = true;
    title.value = '一键发布'
    // selectData.value = []
    // onArticleList(0)
    // if(count.value == selectData.value.length && selectData.value.every((item2:any) => item2.modalOpen === true)) {
    count.value = 0
    const childrenDiv:any = [];
    const builtIns = articleList.value.map((item:any) => `${item.name}  ${item.publishText || ''}  ${item.publishReason || ''}`);
    console.log(articleList.value)
    for (let i in builtIns) {
        const item = createVNode('div', { class: 'item', }, builtIns[i]);
        childrenDiv.push(item);
    }
    const outerDivVNode = createVNode('div', { style: 'padding: 0px;' }, childrenDiv);
    Modal.confirm({
        title: '提示',
        icon: '',
        content: [createVNode('div', { style: 'color:black;' }, `是否确认发布?`),outerDivVNode],
        okText: '确认',
        cancelText: '取消',
        onOk() {
            return new Promise((resolve, reject) => {
                const res = handleOk(resolve, reject, 0)
                console.log(res)
                return res
            }).catch(() => console.log('出错!'))
        },
        onCancel() {
            state.loading = false;
            title.value = '一键发布'
            selectData.value = []
            selectedRows.value = []
            emits('clear-select-data');
            emits('refresh-list');
        },
        class: 'test',
    });
    // }
  }
  // 文章详情
  const onArticleDetails = (articleId:any) => {
    userSiteArticleDetails({articleId: articleId}).then((response:any) => {
        console.log(response)
        const result = response.data.data
        if(result) {
            selectData.value?.forEach((item: any, index:any) => {
                if (articleId === item.articleId) {
                   selectData.value[index]['info'] = result; // 替换为空的内容部分
                   count.value++
                }
            });
        } else {
            selectData.value = selectData.value.filter((item1:any) =>articleId != item1.articleId)
            // count.value--;
            if(selectData.value.length == 0) {
                state.loading = false;
                title.value = '一键发布'
                selectData.value = []
                selectedRows.value = []
                emits('clear-select-data');
                emits('refresh-list');
                message.warning('文章为空');
            }
        }
        console.log('selectData.value',count.value, selectData.value)
        // if(count.value == selectData.value.length && selectData.value.every((item2:any) => item2.modalOpen === true)) {
        // }
    }).catch(err => {console.log(err)})
  }
  // 确认发布
  const handleOk = (resolve:any, reject:any, idx:any) => {
    // 同步执行
    const executeNextOk = (index) => {
        // 判断循环执行完了后执行
        if(index >= selectData.value.length) {
            console.log('sdsdsdsdsddsd')
            state.loading = false;
            title.value = '一键发布'
            selectData.value = []
            selectedRows.value = []
            emits('clear-select-data');
            emits('refresh-list');
            // emits('refresh-data');
            resolve()
            return
        }
        const currentItem = selectData.value[index];
        if(currentItem.cookie) {
          onGetuserinfo(resolve, reject,currentItem.cookie,currentItem.site_id, index) // 从返回的header中解析出token
        }
    }
    executeNextOk(idx)
  }

  // 从返回的header中解析出token
  const onGetuserinfo = async (resolve, reject,cookie,site_id:any, idx:any) => {
    let userInfoObj:any = await GetuserInfo(cookie,site_id)
    console.log('设置返回：',userInfoObj)
    let userInfoResult = JSON.parse(userInfoObj)
    if(userInfoResult.success) {
       onListDel(resolve, reject,idx, false)
    }
  }

  // 文章列表-定时监测数据
  const isPulishArticle = ref(false)
  const onListDel = (resolve:any, reject:any,idx:any, isAfterRelease:any) => {
    let obj = {
        currentPage: 1,
        pageSize: 10,
        search: '',
        type: 'news',
        collection: '',
        clearBeforeFetch: false
    }
    console.log('监测列表')
    articleLists(obj).then((response:any) => {
        const result = response.data.data
        const currentItem = selectData.value[idx];
        if(result.list.length > 0 && result.list[0]['status']) {
            if(currentItem['prev_time']) {
                console.log('时间差',timeDifference(currentItem['prev_time']))
                isPulishArticle.value = timeDifference(currentItem['prev_time'])
                currentItem['prev_time'] = result.list[0]['publish_time']
            } else {
                isPulishArticle.value = timeDifference(result.list[0]['publish_time'])
                currentItem['prev_time'] = result.list[0]['publish_time']
            }
            currentItem['prev_status'] = isPulishArticle.value ? 0 : 1
        } else {
            currentItem['prev_time'] = result.list[0]['publish_time']
            currentItem['prev_status'] = 1
        }
        let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
        // 自动删除审核未通过的文章
        if(arr.length > 0) {
            const executeNext2 = (index) => {
              if(index >= arr.length) {
                console.log(idx)
                setTimeout(() => {
                  onListDel(resolve, reject,idx, false)
                }, 1000)
                return
              }
              if(arr[index]['status'] == 'publish') {
                // 状态已发布-先撤回再删除
                articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                    const result = response.data
                    console.log('articleRemove',result)
                    articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                        console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                        setTimeout(() => {
                            executeNext2(index+1)
                        }, 2000)
                    }).catch(() => {
                        setTimeout(() => {
                            executeNext2(index+1)
                        }, 2000)
                    });
                }).catch(() => {
                    setTimeout(() => {
                        executeNext2(index+1)
                    }, 2000)
                });
              } else {
                articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                    console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                    setTimeout(() => {
                        executeNext2(index+1)
                    }, 2000)
                }).catch(() => {
                    setTimeout(() => {
                        executeNext2(index+1)
                    }, 3000)
                });
              }
            }
            executeNext2(0)
        } else {
            if(!isAfterRelease && isPulishArticle.value && currentItem['prev_status'] == 0) {
                setTimeout(() => {
                    isPulishArticle.value = false
                    onConfirm(resolve, reject,idx)
                }, 1000)
            } else {
                message.warning('不可发布,间隔时间大于15分钟');
                getUserEditPrev(resolve, reject, idx, false)
            }
        }
      }).catch(() => {
        if(!isAfterRelease && isPulishArticle.value) {
            setTimeout(() => {
                isPulishArticle.value = false
                onConfirm(resolve, reject,idx)
            }, 1000)
        } else {
            message.warning('不可发布,间隔时间大于15分钟');
            getUserEditPrev(resolve, reject, idx, false)
        }
      })
  }
  // 获取指定时间和当前时间分钟数--大于15分钟为true
  const timeDifference = (time:any) => {
    // 获取当前时间
    const currentTime:any = new Date();
    // 创建一个指定的时间，例如："2023-04-01T12:00:00"
    const specifiedTime:any = new Date(time);
    // 存储分钟差
    const minutesDifference = ref(0);
    // 存储是否在15到30分钟之间的标志
    const isWithinRange = ref(false);
    // 计算分钟差
    minutesDifference.value = Math.round(Math.abs(currentTime - specifiedTime) / 60000);
    let RandomNumber = Math.floor(Math.random() * (30 - 15 + 1)) + 15
    console.log('计算分钟差', minutesDifference.value, RandomNumber)
    // 判断是否在15到30分钟之间  minutesDifference.value >= 15 && minutesDifference.value <= 30
    isWithinRange.value = minutesDifference.value >= 15;
    return isWithinRange.value
  }
  //获取当前时间
  const formateDate = () => {
    const time = new Date()
    const year = time.getFullYear()
    const month = complement(time.getMonth() + 1)
    const day = complement(time.getDate())
    const hour = complement(time.getHours())
    const minute = complement(time.getMinutes())
    const second = complement(time.getSeconds())
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  }
  //当时间为个位数的时候，在数字前加0
  const complement = (value: number): string => {
    return value < 10 ? `0${value}` : value.toString()
  }
  // 判断是否可以发布
  const getUserEditPrev = (resolve, reject, index:any, isAfter:any) => {
    const currentItem = selectData.value[index];
    let obj = {}
    if(isAfter) {
        obj = {
            prev_time: formateDate(),
            site_id: currentItem['site_id']
        }
    } else {
        obj = {
            site_id: currentItem['site_id'],
            prev_time: currentItem['prev_time'],
            prev_status: currentItem['prev_status']
        }
    }
    console.log(obj,'obj')
    user_editPrev(obj).then((response:any) => {
        console.log('是否可以发布',response)
        if(isAfter) {
            onuserSiteArticleSetRelease(resolve, reject, currentItem.articleId, index)
        } else {
            handleOk(resolve, reject,index + 1)
        }
    }).catch(() => {
        handleOk(resolve, reject,index + 1)
    })
  }
  // 发布文章百家号
  const onConfirm = (resolve:any, reject:any,index:any) => {
    console.log('选中：',selectData.value)
    const currentItem = selectData.value[index];
    let html_content:any = '' // html内容
    const resultData = currentItem.fileLists?.reduce((acc:any, item1:any) => {
        let matchingItem:any = ''
        if(!Array.isArray(currentItem.info['images'])) {
            matchingItem = JSON.parse(currentItem.info['images']).find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
        } else {
            matchingItem = currentItem.info['images'].find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
        }
        if (matchingItem) {
            acc.push({  ...matchingItem,...item1.value }); // 将合并后的对象添加到结果数组中
        }
        return acc;
    }, []); // 初始值为空数组
    // html内容
    if(resultData.length > 0) {
        resultData.forEach((element:any, index:any) => {
        if(index == 0) {
            html_content = currentItem.info.html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
        } else {
            html_content = html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
        }
        });
    } else {
        html_content = currentItem.info.html_content
    }
    if(currentItem.info['min_title'] && !Array.isArray(currentItem.info['min_title']))  {
        JSON.parse(currentItem.info['min_title']).forEach((element:any) => {
            html_content = html_content.replace(element.label,element.html);
        });
    }else  {
        currentItem.info['min_title'].forEach((element:any) => {
            html_content = html_content.replace(element.label,element.html);
        })
    }
    let cover_image = currentItem.fileLists?.find((items:any) => currentItem.info.cover.slice(currentItem.info.cover.lastIndexOf('/') + 1) === items.value.name); // 封面图
    let cover_image2:any = {}
    if(!cover_image) {
        // 无封面图获取第一张图片
        cover_image2 = currentItem.fileLists?.find((_,index:any) => index == 0);
    }
    let vertical_cover_image = currentItem.fileLists?.find((items:any) => currentItem.vertical_cover.slice(currentItem.vertical_cover.lastIndexOf('/') + 1) === items.value.name); // 竖版封面图
    let url = `https://www.huaicaikeyu.cn${currentItem.info.cover}`
    let cover_images_map = JSON.stringify([
        {
            'src': cover_image ? cover_image.value.https_url : cover_image2.value.https_url,
            'origin_src': cover_image ? url : cover_image2.value.https_url
        }
    ])
    console.log(vertical_cover_image, '竖版封面图', currentItem.info.title.length,'标题长度')
    let activityLists:any = [
       {'id': 408, 'is_checked': 1},
       {'id': 'aigc_bjh_status', 'is_checked': 1} // AI创作声明
    ]
    if(currentItem.activity_list.length > 0) {
        let activity_list = currentItem.activity_list.filter((items:any) => items.id == 'ttv');
        if(activity_list.length> 0) {
            activityLists.push({'id': 'ttv', 'is_checked': 1})  // 自动生成视频
        } else {
           activityLists.push({'id': 'ttv', 'is_checked': 0})  // 自动生成视频
        }
    } else{
        activityLists.push({'id': 'ttv', 'is_checked': 0})  // 自动生成视频
    }
    if(currentItem.square_mission_List.length > 0) {
        let mission_List = currentItem.square_mission_List.some((items:any) => items.id == '1600102');
        if(mission_List) {
            activityLists.push({'id': 'task_1600102', 'is_checked': 1})  // 征文任务
        } else {
            activityLists.push({'id': `task_${currentItem.square_mission_List[0].id}`, 'is_checked': 1}) // 征文任务
        }
    }
    console.log('征文任务:', activityLists)
    let objData: any = {
            'type': 'news',
            'title': currentItem.info.title.length > 30 ? currentItem.info.ai_title : currentItem.info.title,
            'content': html_content,
            'creative_method': 'bjh_pc_text',
            'vertical_cover': vertical_cover_image ? vertical_cover_image.value.https_url : '',  // 垂直图片
            'abstract': '',  // 摘要
            'len': html_content.length,
            'activity_list': activityLists,
            'source_reprinted_allow': 0,
            'abstract_from': 1,
            'isBeautify': false,
            'usingImgFilter': false,
            'cover_layout': 'one',
            'cover_images': JSON.stringify([
                {
                    'src': cover_image ? cover_image.value.https_url :  cover_image2.value.https_url,
                    'cropData': {
                        'x': 0,
                        'y': 0,
                        'width': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.width : 300,
                        'height': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.height :  200
                    },
                    'machine_chooseimg': 0,
                    'isLegal': 0
                }
            ]),
            '_cover_images_map': cover_images_map,
            'source': 'choose-remote',
            'cover_source': 'upload',
            'subtitle': '',
            'bjhtopic_id': '',
            'bjhtopic_info': '',
            'clue': '',
            'bjhmt': '',
            'order_id': '',
            'aigc_rebuild': '',
            'image_edit_point': JSON.stringify([
                {'img_type': "cover", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}},
                {'img_type': "body", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}}
            ])
        }
        console.log('objData', objData, html_content)
        articlePublish(objData).then((response:any) => {
            const result = response.data.ret
            console.log('result',result, currentItem.articleId)
            getUserEditPrev(resolve, reject, index, true)
        }).catch((err) => {
            console.log(err)
            message.error(err.message);
            articleList.value.forEach(item1 => {
                if (currentItem.articleId == item1.article_id && item1.is_release == 0) {
                    item1.isPublish = false
                    item1.publishText = '发布失败'
                    item1.publishReason = err.message
                    item1.errorColor3 = 'error'
                }
            });
            handleOk(resolve, reject,index + 1)
        });
  }
  // 设置文章已发布
  const onuserSiteArticleSetRelease = async (resolve:any, reject: any,articleId:any, index:any) => {
    await userSiteArticleSetRelease({articleId: articleId}).then((response:any) => {
        message.success(response.message);
        articleList.value.forEach(item1 => {
            if (articleId == item1.article_id && item1.is_release == 0) {
                item1.isPublish = true
                item1.publishText = '发布成功'
                item1.publishReason = ''
            }
        });
        handleOk(resolve, reject,index + 1)
        // 发布后删除本地缓存文件
        let pathJson = `images_${articleId}`;
        window.electron.ipcRenderer.invoke('delete-file', pathJson+'.zip').then(res => {
            console.log(res)
            if(res.success) {
                console.log('文件删除成功')
            } else {
                console.log('删除文件失败',res.message)
            }
        })
        window.electron.ipcRenderer.invoke('delete-file', pathJson+'.json').then(res => {
            console.log(res)
            if(res.success) {
                console.log('文件删除成功')
            } else {
                console.log('删除文件失败',res.message)
            }
        })
        window.electron.ipcRenderer.invoke('delete-folder', pathJson).then(res => {
            console.log(res)
            if(res.success) {
                console.log('文件夹删除成功')
            } else {
                console.log('删除文件夹失败',res.message)
            }
        })
    }).catch(err => {
        console.log(err)
        state.loading = false;
        title.value = '一键发布'
        selectData.value = []
        selectedRows.value = []
        emits('clear-select-data');
        emits('refresh-list');
    })
  }

  </script>
  
  <style scoped>
  </style>